package Service.Teacher.Imp;

import Dao.DaoFactory;
import Dao.Grade.FinalGradeDao;
import Dao.Grade.GradingDao;
import Dao.Grade.GroupGradeDao;
import Dao.Process.*;
import Dao.TitleAndPaper.PaperDao;
import Dao.TitleAndPaper.TitleDao;
import Entity.Grade.AdviserGrade;
import Entity.Grade.FinalGrade;
import Entity.MyTableData;
import Entity.Process.Medium;
import Entity.Process.ReportDetail;
import Entity.Process.Task;
import Entity.Process.TaskDetail;
import Entity.TitleAndPaper.Paper;
import Service.Teacher.ProcessService;
import Util.DBUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class ProcessServiceImp implements ProcessService {
    private final PaperDao paperDao;
    private final TaskDao taskDao;
    private final TitleDao titleDao;
    private final Connection conn;
    private final MediumDao mediumDao;
    private final ReportDao reportDao;
    private final StageCheckDao stageCheckDao;
    private final TaskDetailDao taskDetailDao;
    private final AdviserGradeDao adviserGradeDao;
    private final FinalGradeDao finalGradeDao;
    private final GradingDao gradingDao;
    private final GroupGradeDao groupGradeDao;
    private final ReportDetailDao reportDetailDao;

    public ProcessServiceImp() {
        paperDao = DaoFactory.getInstance("paperDao");
        taskDao = DaoFactory.getInstance("taskDao");
        titleDao = DaoFactory.getInstance("titleDao");
        mediumDao = DaoFactory.getInstance("mediumDao");
        reportDao = DaoFactory.getInstance("reportDao");
        stageCheckDao = DaoFactory.getInstance("stageCheckDao");
        taskDetailDao = DaoFactory.getInstance("taskDetailDao");
        adviserGradeDao = DaoFactory.getInstance("adviserGradeDao");
        finalGradeDao = DaoFactory.getInstance("finalGradeDao");
        gradingDao = DaoFactory.getInstance("gradingDao");
        groupGradeDao = DaoFactory.getInstance("groupGradeDao");
        reportDetailDao = DaoFactory.getInstance("reportDetailDao");
        conn = DBUtil.getConnByDruid();
    }

    @Override
    public MyTableData getAllPaper(String queryKey, Integer offset, Integer limit, String tNo, String state, Integer type) {
        //查询所有的论文
        List<Paper> papers = paperDao.getAllPaper(queryKey, offset, limit, tNo, type, conn);
        if (papers.size() > 0) {
            for (Paper paper : papers) {
                //根据每个论文中的选题ID来查询 选题的详情
                paper.setTitle1(titleDao.getTitleById(paper.getXtId(), conn));
                //根据论文所处于的状态 查询关联的不同对象
                switch (state) {
                    case "任务书":
                        paper.setTask(taskDao.getTaskBySNO(paper.getSno(), conn));
                        break;
                    case "中期检查":
                        paper.setMedium(mediumDao.getMediumBySNO(paper.getSno(), conn));
                        break;
                    case "开题报告":
                        paper.setReport(reportDao.getReportBySNO(paper.getSno(), conn));
                        break;
                    case "初稿":
                        paper.setStageCheck(stageCheckDao.getStageCheckBySNOAndPhase(paper.getSno(), "初稿", conn));
                        break;
                    case "定稿":
                        paper.setStageCheck(stageCheckDao.getStageCheckBySNOAndPhase(paper.getSno(), "定稿", conn));
                        break;
                    case "终稿":
                        paper.setStageCheck(stageCheckDao.getStageCheckBySNOAndPhase(paper.getSno(), "终稿", conn));
                        break;
                    case "定稿评分":
                        paper.setAdviserGrade(adviserGradeDao.getAdviserGradeBySNO(paper.getSno(), conn));
                        break;
                    default:
                        break;
                }
            }
        }
        DBUtil.closeConn(conn);
        return new MyTableData(0, "", papers.size(), papers);
    }

    @Override
    public Boolean addAssigmentByTNO(Task task, TaskDetail taskDetail) {
        boolean flag = false;
        try {
            conn.setAutoCommit(false);//取消事务自动提交
            Task task1 = taskDao.getTaskBySNO(task.getSno(), conn);
            //向task表插入任务书
            int rs1, rs2;
            if (task1 == null || task1.getTaskId() == null) {   // 如果是第一次下达任务书 就插入
                rs1 = taskDao.insertTask(task, conn);
                //获取插入的ID
                task1 = taskDao.getTaskBySNO(task.getSno(), conn);
                taskDetail.setTaskId(task1.getTaskId());
                rs2 = taskDetailDao.insetTaskDetail(taskDetail, conn);
            } else { // 如果是任务书不通过
                rs1 = taskDao.updateCheck(task1.getTaskId(), null, null, "审核中", conn);
                taskDetail.setTaskId(task1.getTaskId());
                rs2 = taskDetailDao.updateTaskDetailById(taskDetail, conn);
            }
            //向task_detail插入任务书详情 两者要么都成功 要么都失败

            if (rs1 == 1 && rs2 == 1) {
                conn.commit();//提交事务
                flag = true;
            } else {
                conn.rollback();
            }
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBUtil.closeConn(conn);
        }
        return flag;
    }

    @Override
    public TaskDetail getTaskDetailById(Integer id) {
        TaskDetail taskDetail = taskDetailDao.getTaskDetailById(id, conn);
        DBUtil.closeConn(conn);
        return taskDetail;
    }

    @Override
    public Boolean addMedium(Medium medium) {
        boolean flag;
        int sum = mediumDao.getSumBySNO(medium.getSno(), conn);
        if (sum == 0) {
            flag = mediumDao.insertMedium(medium, conn) == 1;
        } else {
            flag = mediumDao.updateBySNO(medium, conn) == 1;
        }
        DBUtil.closeConn(conn);
        return flag;
    }

    @Override
    public Boolean addAdviserGrade(AdviserGrade grade) {
        boolean flag = false;
        try {
            conn.setAutoCommit(false);//取消事务自动提交
            //向指导老师的评分表插入一条数据
            int res1 = adviserGradeDao.addAdviserGrade(grade, conn);
            AdviserGrade newGrade = adviserGradeDao.getAdviserGradeBySNO(grade.getSno(), conn);
            int gradeSum = newGrade.getGrade1() + newGrade.getGrade2() + newGrade.getGrade3() + newGrade.getGrade4() + newGrade.getGrade5() + newGrade.getGrade6();
            String SNO = newGrade.getSno();
            Integer advID = newGrade.getId();
            //总分表插入总分和学号 和id
            FinalGrade finalGrade = new FinalGrade();
            finalGrade.setGrade1(gradeSum);
            finalGrade.setGrade1Id(advID);
            finalGrade.setSno(SNO);
            int res2 = finalGradeDao.insetAdsGrade(finalGrade, conn);
            //如果同意参加答辩 则往评阅老师 和答辩小组插入数据 等待 分配评阅老师和答辩小组
            if ("是".equals(grade.getIsReply())) {
                int res4 = groupGradeDao.insertSNOAndTNO(SNO, grade.getTno(), conn);
                if (res1 == 1 && res2 == 1  && res4 == 1) {
                    conn.commit();//提交事务
                    flag = true;
                } else {
                    conn.rollback();
                }
            } else {
                if (res1 == 1 && res2 == 1) {
                    conn.commit();//提交事务
                    flag = true;
                } else {
                    conn.rollback();
                }
            }
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBUtil.closeConn(conn);
        }
        return flag;
    }

    @Override
    public ReportDetail getReportDetailById(Integer id) {
        ReportDetail reportDetail = reportDetailDao.getReportDetailById(id, conn);
        DBUtil.closeConn(conn);
        return reportDetail;
    }
}
